<?php

namespace App\Admin\Models;

use Illuminate\Database\Eloquent\Collection;use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class AdminUser extends Authenticatable
{
    use Notifiable;

    protected $rememberTokenName = null;

    protected $fillable = ['name', 'password'];

    // 用户有哪些角色
    public function roles()
    {
        return $this->belongsToMany(AdminRole::class, 'admin_user_roles', 'user_id', 'role_id')->withPivot(['user_id', 'role_id']);
    }

    // 判断用户是否有某些角色中的任意一个
    public function isInRoles(Collection $roles)
    {
        // intersect求交集
        return !!$roles->intersect($this->roles)->count();
    }

    // 给用户分配角色
    public function assignRole(AdminRole $role)
    {
        return $this->roles()->save($role);
    }

    // 删除用户的某个角色
    public function deleteRole($role)
    {
        return $this->roles()->detach($role);
    }

    // 用户是否有权限
    public function hasPermission($permission)
    {
        // 用户角色和权限角色是否有交集
        return $this->isInRoles($permission->roles);
    }

}
